﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SaturniLibrary.MIGS.V1
{
    public class ThreePartyRequest : SortedDictionary<string, string>
    {
        public string VirtualPaymentClientUrl { get; set; }

        public string SecureSecret { get; set; }

        public ThreePartyRequest() : base(StringComparer.Ordinal)
        {
            this.Add("vpc_Version", "1");
            this.Add("vpc_Command", "pay");
        }

        public string ToRequestUrl()
        {
            Validate();
            string url = VirtualPaymentClientUrl+"?";
            url = this.Aggregate(url, (current, pair) => current + string.Format("{0}={1}&", pair.Key, HttpUtility.UrlEncode(pair.Value)));
            if (!string.IsNullOrWhiteSpace(SecureSecret))
            {
                url += "vpc_SecureHash=" + MIGSHelper.GetSearchHash(SecureSecret, this);
            }
            return url;
        }

        public string ToDataString()
        {
            return string.Format("{{VirtualPaymentClientUrl={0}, SecureSecret={1},{2}}}", VirtualPaymentClientUrl, SecureSecret, string.Join(",", this.Select(kv => kv.Key.ToString() + "=" + kv.Value.ToString()).ToArray()));
        }
        
        private void Validate()
        {
            if (string.IsNullOrWhiteSpace(VirtualPaymentClientUrl))
            {
                throw new Exception("VirtualPaymentClientUrl is required");
            }
            if (!this.ContainsKey("vpc_AccessCode"))
            {
                throw new Exception("AccessCode is required");
            }

            if (!this.ContainsKey("vpc_Merchant"))
            {
                throw new Exception("Merchant is required");
            }

            if (!this.ContainsKey("vpc_MerchTxnRef"))
            {
                throw new Exception("MerchTxnRef is required");
            }

            if (!this.ContainsKey("vpc_Locale"))
            {
                throw new Exception("Locale is required");
            }

            if (!this.ContainsKey("vpc_Amount"))
            {
                throw new Exception("Amount is required");
            }
            try
            {
                int.Parse(this["vpc_Amount"]);
            }
            catch
            {
                throw new Exception("Amount must be integer type");
            }

            if (!this.ContainsKey("vpc_ReturnURL"))
            {
                throw new Exception("ReturnURL is required");
            }

        }
    }
}
